package svn

import (
	"errors"
	"os"
	"svntool/application/models/config"
	"svntool/application/models/linetool/cmd"
	"svntool/application/models/linetool/cmd/version"
	"svntool/application/models/util/file"
	"svntool/db/tables"

	"github.com/astaxie/beego/context"
)

/**
 * svn版本管理注册
 */
type SvnReg struct {
}

//环境监测
func (sr *SvnReg) Check(ctx *context.Context) (bool, error) {
	//svn环境
	version_cmd := version.VersionCmd{}
	cmd_exector := cmd.CmdAbstruct{&version_cmd, "svn"}
	output, err := cmd_exector.Exec("")
	if err != nil {
		return false, err
	}
	if output == "" {
		//没有检测到软件安装，进行提示
		myos, artiture := config.GetSystemInfo()
		if myos == "windows" {
			if artiture == "amd64" {
				return false, errors.New("未检测到svn，点击<a href=\"https://sliksvn.com/pub/Slik-Subversion-1.9.7-x64.zip\" target=\"_blank\">链接</a>下载安装并设置好环境变量后重试")
			} else {
				return false, errors.New("未检测到svn，点击<a href=\"https://sliksvn.com/pub/Slik-Subversion-1.9.7-win32.zip\" target=\"_blank\">链接</a>下载安装并设置好环境变量后重试")
			}
		} else if myos == "ubuntu" {
			return false, errors.New("未检测到svn，请执行 <font color='red'>sudo apt-get install subversion</font> 命令安装")
		} else if myos == "centos" {
			return false, errors.New("未检测到svn，请执行 <font color='red'>sudo yum install subversion</font> 命令安装")
		} else if myos == "darwin" {
			return false, errors.New("未检测到svn，请执行 <font color='red'>sudo brew install svn</font> 命令安装")
		}
	}
	//svn路径
	svn_place := ctx.Input.Query("svnplace")
	result, err := file.PathPrivlege(svn_place)
	if err != nil {
		return false, errors.New("<font color='red'>" + svn_place + "</font> 路径不存在")
	}
	result = result & os.FileMode(448)
	if uint32(result) != 448 {
		return false, errors.New("没有足够权限访问该路径，请执行 <font color='red'>sudo chmod -R 700 " + svn_place + "</font>")
	}
	return true, nil
}

//注册
func (sr *SvnReg) Reg(ctx *context.Context) (bool, error) {
	svn_place := ctx.Input.Query("svnplace")

	go func() {
		//保存SVN仓库
		config := tables.Config{}
		config.SaveSvnPlace(svn_place)
	}()
	return true, nil
}
